package com.gxa.portal.interceptor;


import com.gxa.common.result.Result;
import com.gxa.portal.utils.JsonUtils;
import com.gxa.portal.utils.ResponseUtils;
import com.gxa.user.pojo.User;
import com.gxa.user.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by bill on 2021/1/6
 **/
public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            Result result = new Result(500010, "没有登录!");
            ResponseUtils.responseJson(response, JsonUtils.objectToJson(result));
           return false;
        }

        User user = userService.queryUserByToken(token);
        if(user==null){
            Result result = new Result(500010, "没有登录!");
            ResponseUtils.responseJson(response,JsonUtils.objectToJson(result));
            return false;
        }

        //绑定用户到当前线程
        //因为service是使用dubbo远程调用，都不在一个项目，更不要说一个线程了，所以使用传统
        //方法无法向service隐式传参
        UserThreadLocal.set(user);

        //dubbo隐式传参
        RpcContext.getContext().setAttachment("userId",user.getId()+"");



        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        //移除当前线程的用户
        UserThreadLocal.remove();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
